<?php
header("Content-type: text/plain; charset=utf-8", true);

if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET["service-source"])) {
    echo file_get_contents(__FILE__);
    return;
}

session_start();

require_once("lib/jsonss.php");

if (!isset($_SESSION["TimerService.Timers"]))
    $_SESSION["TimerService.Timers"] = array();

class TimerService extends JSONSSService {
    public function SetTimer($p) {
        if (!is_string($p))
            throw new JSONSSError(501, "TimerService: SetTimer() expects string parameter");
        if (isset($_SESSION["TimerService.Timers"][$p]))
            throw new JSONSSError(501, "TimerService: timer '" . $p . "' already exists");
        $tmr = new stdClass();
        $tmr->id = $p;
        $tmr->expires = time()+15;
        $_SESSION["TimerService.Timers"][$tmr->id] = $tmr;
        $this->fire_event("Created", $p);
    }

    public function CancelOrUnsetTimer($p) {
        if (!is_string($p))
            throw new JSONSSError(501, "TimerService: CancelOrUnsetTimer() expects string parameter");
        if (!isset($_SESSION["TimerService.Timers"][$p]))
            throw new JSONSSError(501, "TimerService: timer '" . $p . "' not exists");
        unset($_SESSION["TimerService.Timers"][$p]);
        $this->fire_event("Removed", $p);
    }

    public function __construct() {
        $this->add_method("SetTimer", "set-timer");
        $this->add_method("CancelOrUnsetTimer", "unset-timer");
        $this->add_event("Expired");
        $this->add_event("Created");
        $this->add_event("Removed");
    }

    public function ping() {
        foreach ($_SESSION["TimerService.Timers"] as $tn => $tmr) {
            if ($tmr->expires < time())
                $this->fire_event("Expired", $tn);
            if ($tmr->expires < time()-15) {
                $this->fire_event("Removed", $tn);
                unset($_SESSION["TimerService.Timers"][$tn]);
            }
        }
    }
}

$server = new JSONSSServer();
$server->add_service(new TimerService(), "TimerService", "timer-service");
$server->process_request();

session_commit();
